<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head th:replace="common/common_header :: common_header(~{::title},~{::link},~{})">
    <title>商品分类</title>
    <link href="js/jquery-confirm/jquery-confirm.min.css" th:href="@{/js/jquery-confirm/jquery-confirm.min.css}" rel="stylesheet">
    <link href="/js/ztree-3.5/metroStyle/metroStyle.css" rel="stylesheet" th:href="@{/css/metroStyle/metroStyle.css}" >
</head>
<body>
<div class="container-fluid p-t-15">
    <div class="row">
        <div class="col-lg-6">
            <div class="card">
                <header class="card-header">
                    <div class="card-title">商品分类</div>
                    <ul class="card-actions">
                        <li class="dropdown">
                            <a href="#!" class="dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">更多</a>
                            <div class="dropdown-menu dropdown-menu-right">
                                <a class="dropdown-item" href="#!"> <i class="mdi mdi-arrow-collapse-down"></i> 下载数据</a>
                                <a class="dropdown-item" href="#!"> <i class="mdi mdi-arrow-collapse-up"></i> 上传数据</a>
                                <div class="dropdown-divider"></div>
                                <a class="dropdown-item" href="#!"> <i class="mdi mdi-settings"></i> 参数设置</a>
                            </div>
                        </li>
                        <li>
                            <a href="#!" data-toggle="tooltip" title="" data-original-title="添加根节点"><i class="mdi mdi-undo"></i></a>
                        </li>
                        <li>
                            <a href="#!" data-toggle="tooltip" title="" data-original-title="重做"><i class="mdi mdi-redo"></i></a>
                        </li>
                        <li>
                            <a href="#!" data-toggle="tooltip" title="" data-original-title="刷新"><i class="mdi mdi-refresh"></i></a>
                        </li>
                    </ul>
                </header>
                <div class="card-body">
                    <ul id="treeData" class="ztree"></ul>
                </div>
            </div>
        </div>
        <div class="col-lg-6">
            <div class="card">
                <header class="card-header"><div class="card-title">分类信息</div></header>
                <div class="card-body">
                    <div class="form-group">
                        <label for="nodeName">当前选择</label>
                        <input class="form-control" style="background-color: #4fbfc9!important; color: #ffffff!important;" id="nodeName" type="text" placeholder="此处为当前选择的分类信息..." readonly>
                    </div>
                    <form class="form-horizontal" id="form" onsubmit="return false" action="#" method="post"  >
                        <div class="form-group">
                            <label for="name">分类名称</label>
                            <input type="text" class="form-control" id="name" name="name"  autocomplete="off" placeholder="分类名称">
                            <input type="hidden" class="form-control" id="id" name="id">
                        </div>
                        <div class="form-group">
                            <label >分类状态</label>
                            <div class="form-check">
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input" type="radio" name="status" id="status1" value="1">
                                    <label class="form-check-label" for="status1">正常</label>
                                </div>
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input" type="radio" name="status" id="status2" value="2">
                                    <label class="form-check-label" for="status2">异常</label>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="sortOrder">分类排序</label>
                            <input type="text" class="form-control" id="sortOrder"  autocomplete="off" name="sortOrder" placeholder="分类排序">
                        </div>
                        <div class="form-group">
                            <label for="create">创建时间</label>
                            <input type="text" class="form-control" id="create"  autocomplete="off" name="created" readonly>
                        </div>
                        <div class="form-group">
                            <label for="update">修改时间</label>
                            <input type="text" class="form-control" id="update"  autocomplete="off" name="updated" readonly>
                        </div>
                    </form>
                    <button type="button" class="btn btn-primary" onclick="submit()">提交</button> <button type="reset" class="btn btn-cyan">重填</button>
                </div>
        </div>
    </div>
</div>
</div>
<script type="text/javascript" th:src="@{/js/jquery.min.js}"></script>
<script type="text/javascript" th:src="@{/js/popper.min.js}"></script>
<script type="text/javascript" th:src="@{/js/bootstrap.min.js}"></script>
<script type="text/javascript" th:src="@{/js/main.min.js}"></script>
<script type="text/javascript" th:src="@{/js/form-util.js}"></script>
<script type="text/javascript" th:src="@{/js/ztree-3.5/jquery.ztree.core.js}"></script>
<script type="text/javascript" th:src="@{/js/ztree-3.5/jquery.ztree.exedit.js}"></script>
<script type="text/javascript" src="js/jquery-confirm/jquery-confirm.min.js" th:src="@{/js/jquery-confirm/jquery-confirm.min.js}"></script>
<script type="text/javascript">
    var setting = {
        view: {
            selectedMulti: false
        },
        async: {
            enable: true,
            url:"/cat/getGoodsCatList",
            autoParam:["id", "name", "level"],
            // contentType: "application/json; charset=UTF-8",
            otherParam:{"pid":0},
            dataFilter: filter
        },
        edit: {
            enable: true,
            editNameSelectAll: true,
            removeTitle: "删除",
            showRemoveBtn: showRemoveBtn,
            showRenameBtn: showRenameBtn,
        },
        data: {
            key : {
                name : "name" //展开树的名字
            }
        },
        callback: {
            beforeClick: beforeClick,
            beforeAsync: beforeAsync,
            onAsyncError: onAsyncError,
            onAsyncSuccess: onAsyncSuccess,
            beforeRemove:beforeRemove,
            // beforeRename:beforeRename,
            onRemove: onRemove,
        }
    };

    function filter(treeId, parentNode, childNodes) {
        if (!childNodes) return null;
        for (var i=0, l=childNodes.length; i<l; i++) {
            childNodes[i].name = childNodes[i].name.replace(/\.n/g, '.');
        }
        return childNodes;
    }

    //用户可判定是否进行删除操作 如果返回 false，zTree 将不删除节点，也无法触发 onRemove 事件回调函数
    function beforeRemove(treeId,treeNode){
        console.log(treeId,treeNode)
        let name = treeNode.name.trim();
        let checkName = $("#nodeName").val();
        if (name == checkName){
            $("#nodeName").val('')
        }
        $.confirm({
            title: '删除 '+name+' 警告',
            icon: 'mdi mdi-alert',
            type: 'red',
            content: '删除当前节点和所有子节点',
            buttons: {
                confirm: {
                    btnClass: 'btn-red',
                    text: '删除',
                    action: function() {
                        $.post("/cat/delGoodsCat",{"id":treeNode.id},function (res){
                            if (res.code === 0){
                                $.alert('你删除'+name+'的所有子节点！');
                            }
                            else{
                                $.alert(res.msg);
                            }
                            refreshParentNode()
                        })
                    }
                },
                cancelAction: {
                    text: '取消',
                    action: function() {
                        $.alert(name+'刚刚得救了！');
                    }
                }
            }
        });
        return true
    }


    function beforeRename(treeId, treeNode, newName, isCancel){
        if (newName.trim().length === 0) {
            setTimeout(function() {
                var zTree = $.fn.zTree.getZTreeObj("treeData");
                zTree.cancelEditName();
                alert("节点名称不能为空.");
            }, 0);
            return false;
        }
        let name = treeNode.name;
        $.confirm({
            title: '修改 '+name+' 警告',
            icon: 'mdi mdi-alert',
            type: 'red',
            content: '确定要改个名字吗',
            buttons: {
                confirm: {
                    btnClass: 'btn-red',
                    text: '修改',
                    action: function() {
                        $.post("/region/updateRegion",{"id":treeNode.id,"name":newName.trim()},function (res){
                            if (res.code === 0){
                                $.alert('修改成功！');
                                refreshParentNode()
                            }
                        })
                    }
                },
                cancelAction: {
                    text: '取消',
                    action: function() {
                        $.alert(name+'刚刚得救了！');
                    }
                }
            }
        });
        return true;

    }

    //执行删除之前
    function onRemove(e, treeId, treeNode) {
        console.log(e, treeId, treeNode)
    }

    //显示删除按钮
    function showRemoveBtn(treeId, treeNode) {
        return true;
    }

    //显示修改按钮
    function showRenameBtn(treeId,treeNode){
        return false;
    }

    /**
     * 点击之前
     * @param treeId
     * @param treeNode 被单击的节点 JSON 数据对象
     * @returns {boolean}
     */
    function beforeClick(treeId, treeNode) {
        console.log(treeNode)
        $("#nodeName").val(treeNode.name);

        var id = treeNode.id
        $.get("/cat/getGoodsCat",{"id":id},function (res){
            if (res.code === 0){
                $("#form").setFormValue({
                    "id":res.data.id,
                    "name": res.data.name,//input标签
                    "status": res.data.status,//多行文本
                    "select":"2",//选择标签
                    "sortOrder":res.data.sortOrder,
                    //多选框
                    "test": {
                        1: true,
                        2: false,
                        3: true
                    },
                    "checkboxtest": true,//多选框2
                    "created": formatDate(res.data.created),//多选框2
                    "updated":formatDate(res.data.updated)
                })
            }
            else{

            }
        })

        //添加进本地 提交表单时使用$.param({"name":1213}) + ‘&’传递参数
        let node = {}
        node.id = treeNode.id
        node.name = treeNode.name
        node.code = treeNode.code
        node.parentCode = treeNode.parentCode
        node.level = treeNode.level
        node.charin = treeNode.charin
        sessionStorage.setItem("tree",JSON.stringify(node));
        return true;
    }
    var log, className = "dark";
    function beforeAsync(treeId, treeNode) {
        className = (className === "dark" ? "":"dark");
        showLog("[ "+getTime()+" beforeAsync ]&nbsp;&nbsp;&nbsp;&nbsp;" + ((!!treeNode && !!treeNode.name) ? treeNode.name : "root") );
        return true;
    }
    function onAsyncError(event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown) {
        showLog("[ "+getTime()+" onAsyncError ]&nbsp;&nbsp;&nbsp;&nbsp;" + ((!!treeNode && !!treeNode.name) ? treeNode.name : "root") );
    }
    function onAsyncSuccess(event, treeId, treeNode, msg) {
        showLog("[ "+getTime()+" onAsyncSuccess ]&nbsp;&nbsp;&nbsp;&nbsp;" + ((!!treeNode && !!treeNode.name) ? treeNode.name : "root") );
    }

    function showLog(str) {
        if (!log) log = $("#log");
        log.append("<li class='"+className+"'>"+str+"</li>");
        if(log.children("li").length > 8) {
            log.get(0).removeChild(log.children("li")[0]);
        }
    }
    function getTime() {
        var now= new Date(),
            h=now.getHours(),
            m=now.getMinutes(),
            s=now.getSeconds(),
            ms=now.getMilliseconds();
        return (h+":"+m+":"+s+ " " +ms);
    }

    function refreshNode(e) {
        var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
            type = e.data.type,
            silent = e.data.silent,
            nodes = zTree.getSelectedNodes();
        if (nodes.length == 0) {
            alert("请先选择一个父节点");
        }
        for (var i=0, l=nodes.length; i<l; i++) {
            zTree.reAsyncChildNodes(nodes[i], type, silent);
            if (!silent) zTree.selectNode(nodes[i]);
        }
    }

    /**
     * 渲染
     */
    $(document).ready(function(){
        $.fn.zTree.init($("#treeData"), setting);
        $("#refreshNode").bind("click", {type:"refresh", silent:false}, refreshNode);
        $("#refreshNodeSilent").bind("click", {type:"refresh", silent:true}, refreshNode);
        $("#addNode").bind("click", {type:"add", silent:false}, refreshNode);
        $("#addNodeSilent").bind("click", {type:"add", silent:true}, refreshNode);
    });

    /**
     * 刷新当前选中的节点
     */
    function refresh(){
        var zTree = $.fn.zTree.getZTreeObj("treeData")
        let type = 'refresh'
        let silent = false;

        //获取当前选中的节点
        var nodes = zTree.getSelectedNodes()

        //加载加载节点的子节点
        zTree.reAsyncChildNodes(nodes[0],type,silent);
    }

    /**
     * 刷新当前节点的父节点
     */
    function refreshParentNode(){
        var zTree = $.fn.zTree.getZTreeObj("treeData")
        let type = 'refresh'
        let silent = false;

        //获取当前选中的节点
        var nodes = zTree.getSelectedNodes()

        //根据JSON的唯一标识 获取节点的JSON对象
        var parentNode = zTree.getNodeByTId(nodes[0].parentTId)

        //选中指定节点
        zTree.selectNode(parentNode)

        //加载加载节点的子节点
        zTree.reAsyncChildNodes(parentNode,type,silent);
    }


    //防止表单重复提交
    let flag = false;
    function submit(){
        console.log($('#form').serialize())

        if (flag)return ;
        flag = true
        let nodeName = $("#nodeName").val();
        if (nodeName===undefined||nodeName===""){
            $.alert({
                title: '异常提示',
                icon: 'mdi mdi-alert',
                type: 'orange',
                content: '更新分类信息异常',
            });
            return ;
        }

        $.ajax({
            type: "POST",
            dataType: "json",
            url: "/cat/updateGoodsCat" ,
            data: $('#form').serialize(),
            success: function (res) {
                console.log(res);//打印服务端返回的数据(调试用)
                if (res.code === 0) {
                    $.alert({
                        title: '提示信息',
                        icon: 'mdi mdi-check-decagram',
                        type: 'green',
                        content: '更新成功',
                    });
                    refreshParentNode();

                }
                else{
                    $.alert({
                        title: res.msg,
                        icon: 'mdi mdi-alert',
                        type: 'green',
                        content: res.data,
                    });
                }
                flag = false;
            },
            error : function(e) {
                $.alert({
                    title: res.msg,
                    icon: 'mdi mdi-alert',
                    type: 'green',
                    content: res.data,
                });
                flag = false;
            }
        });
    }
</script>
</body>
</html>